App({
    globalData: {
        barName: 'index'
    },
    onLaunch: function () {
        // 隐藏原生的tabbar
        // wx.hideTabBar()
      this.wxLogin();
    },
  //微信登陆
  wxLogin() {
    var that = this;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId
        that.getOpenid(res.code);
      }
    })
    wx.onNetworkStatusChange(function (res) {
      if (res.networkType == 'none') {
        that.showToast('网络连接断开');
      }
    })
  },
  //获取openid,session_key
  getOpenid: function (code) {
    var that = this;
    that.ajax({
      url: 'api/Wx/getUserOpenid',
      method: "POST",
      data: {
        code: code
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.code == 1000) {
          wx.setStorageSync("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo0LCJwaG9uZSI6IjE4ODgzODgwNDQ4IiwiZXhwaXJ5X3RpbWUiOjE1NTgzNjQ0MjF9.aYSfvPRwe2hM-agwm1ZLFNjc9UL0-EIDqfD2V1jinaA");
          wx.setStorageSync('session_key', res.data.data.session_key);
          wx.setStorageSync('openid', res.data.data.openid);
        }
      }
    })
  },

  //ajax 请求
  ajax(model) {
    var that = this;

    //拼接url
    if (model.url.indexOf("https://") == -1 && model.url.indexOf("http://") == -1) {
        model.url = "https://jzrxh.xiaolu-media.com/" + model.url;
    }
    //get参数拼接
    if (model.method == "get" && model.data !== undefined) {
      for (let k in model.data) {
        if (model.data[k].toString() !== '') {
          model.url = model.url + "&" + k + "=" + model.data[k];
        }
      }
      model.data = '';
    }
    //返回Promise对象
    return new Promise(
      function (resolve) {
        var token = wx.getStorageSync('token');
        wx.request({
          method: model.method,
          url: model.url,
          header: {
            'token': token, // 默认值
          },
          data: model.data,
          success: (resolve) => {
            model.success(resolve);
          },
          error: () => {
            model.error('网络请求失败');
          }
        })
      }
    )
  },
})